//
//  MainModule.m
//  bsl-sdk
//
//  Created by Fanty on 13-11-28.
//
//

#import "CubeModule.h"
#import "CubeHomeIPhoneViewController.h"
#import "IsolatedStorageFile+CubeLogic.h"
#import "DataCenter+Cube.h"
#import "CubesModel.h"
#import "BSLCubeConstant.h"

#import <chameleon-ios-sdk/CApplication.h>
#import <MainModuleSDK/CViewController.h>

@interface CubeModule()
-(void)delaySyncMessage:(NSString*)messageId;
@end

@implementation CubeModule
@synthesize cubeModuleManager;
@synthesize autoDownloadCheckingOperator;
@synthesize messageManager;
@synthesize accountManager;

-(id)init{
    self=[super init];
    if(self){
        isActive=YES;
        firstSyncNotification=YES;
    }
    return self;
}


- (BOOL)application:(CApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions{
    if(launchOptions!=nil){
        NSDictionary* dictionary = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
        
        apnsMessageId=[dictionary objectForKey:@"id"];
    }
    return YES;
}

-(void)startDispatchAsync{
    [IsolatedStorageFile copyFolderAtPath:[IsolatedStorageFile cubeResourceDirectory] toPath:[IsolatedStorageFile cordovaRootDirectory] error:nil];
}

-(void)delaySyncMessage:(NSString*)messageId{
    [messageManager syncMessageById:messageId routing:YES];
}


-(void)finishDispatchAsync{
    cubeModuleManager=[[CubeModuleManager alloc] init];
    autoDownloadCheckingOperator=[[AutoDownloadCheckingOperator alloc] init];
    messageManager=[[MessageManager alloc] init];
    accountManager=[[AccountManager alloc] init];
    
}


-(UIViewController*)startMainViewControllerWithParams:(NSDictionary*)dict{
    return [[CubeHomeIPhoneViewController alloc] init];
}


-(void)syncModuleList{
    //如果是第一次同步模块
    if(firstSyncNotification){
        firstSyncNotification=NO;
        //如果是从推送消息进入app
        if([apnsMessageId length]>0){
            [self performSelector:@selector(delaySyncMessage:) withObject:apnsMessageId afterDelay:1.5f];
            apnsMessageId=nil;
        }
        else{
            [messageManager performSelector:@selector(syncMessage) withObject:nil afterDelay:1.0f];
        }
        
        //打开权限同步
        [accountManager syncAuth:NO];

    }
}


-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
    NSString* messageId=[userInfo objectForKey:@"id"];
    if([messageId length]>0){
        [messageManager syncMessageById:messageId routing:!isActive];
    }
}

- (void)applicationDidBecomeActive:(UIApplication *)application{
    isActive=YES;
}

- (void)applicationWillResignActive:(UIApplication *)application{
    isActive=NO;
}



@end
